package cn.edu.bupt.freewings.forum.persistence;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class EntityManagerHelper {
	private static EntityManagerFactory emf = null;
	private static ThreadLocal<EntityManager> threadLocal;
	static{
		emf = Persistence.createEntityManagerFactory("forum_db");
		threadLocal = new ThreadLocal<EntityManager>();
	}
	
	public static EntityManager getEntityManager(){
		if(threadLocal.get() == null){
			threadLocal.set(emf.createEntityManager());
		}
		return threadLocal.get();
	}
	
	public static void closeEntityManager(){
		if(threadLocal.get() != null)
			threadLocal.get().close();
	}
	
	public static void beginTransaction(){
		if(getEntityManager().getTransaction().isActive())
			getEntityManager().getTransaction().rollback();
		getEntityManager().getTransaction().begin();
	}
	
	public static void commit(){
		getEntityManager().getTransaction().commit();
	}
	
	public static void rollback(){
		getEntityManager().getTransaction().rollback();
	}
	
	public static void main(String args[]){
		User user = new UserDAO().findById(1);
		System.out.println(user);
	}
}
